package com.sibu.yx.promotion.web.support.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.doubo.common.threadlocal.SerialNo;

import lombok.extern.slf4j.Slf4j;

/**
 * Created with IntelliJ IDEA.
 * User: qiujingwang
 * Date: 2016/3/23
 * Description: 计算controller 的执行时间
 */
@Slf4j
public class TimeInteceptor extends HandlerInterceptorAdapter {

    private static final ThreadLocal<Long> timeThreadLocal = new ThreadLocal<Long>();

    //before the actual handler will be executed
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler)
            throws Exception {
        if(log.isInfoEnabled()){
            long startTime = System.currentTimeMillis();
            timeThreadLocal.set(startTime);
        }
        return true;
    }

    public void afterCompletion(HttpServletRequest arg0,
                                HttpServletResponse arg1, Object handler, Exception arg3)
            throws Exception {
        if(log.isInfoEnabled()){
            long startTime = timeThreadLocal.get();

            long endTime = System.currentTimeMillis();

            long executeTime = endTime - startTime;

            HandlerMethod handlerMethod = (HandlerMethod) handler;
            String clazzName = handlerMethod.getBeanType().getSimpleName();
            String methodName = handlerMethod.getMethod().getName();

            log.info("[{}] [{}.{}] executeTime : {} ms", SerialNo.getSerialNo(),
                    clazzName, methodName, executeTime);
        }
    }
}
